package com.ffapp.f9164.td.user;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.BasisActivity;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.util.MessageUtil;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.leon.lfilepickerlibrary.LFilePicker;

import java.io.File;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;
import my.BleUtils;
import my.DialogUtils;
import my.FileUtils;

public class WareSoftUpdateActivity extends BasisActivity {

    private boolean isFinish = false;

    @BindView(R.id.tv_content)
    TextView tvContent;

    private static String UPGRADE_NOTICE = "4e";

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.activity_ware_soft_update);
        setTitle("固件升级");
        setTitleLeftButton(R.drawable.base_icon_back_white,new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @OnClick(R.id.btn_update)
    public void update(){
        String file_media = Constants.DIR_FIRM_WARE;
                File destDir = new File(file_media);
                if (!destDir.exists()) {// 判断文件夹是否存在
                    destDir.mkdirs();
                }

                new LFilePicker()
                        .withActivity(WareSoftUpdateActivity.this)
                        .withRequestCode(REQUEST_FIRM_WARE_SHARE)
                        .withTitle("文件选择")
                        .withBackgroundColor("#0396FF")
                        .withMutilyMode(false)
                        .withMaxNum(1)
                        .withStartPath(Constants.DIR_FIRM_WARE)//指定初始显示路径
                        .withFileFilter(new String[]{"txt", "bin"})
                        .start();
    }

    private final static int REQUEST_FIRM_WARE_SHARE = 42;        //从固定文件夹返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            tvContent.setVisibility(View.VISIBLE);
            showToast("升级成功");
//        if ( requestCode == REQUEST_FIRM_WARE_SHARE  && resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
//            String path = null;
//            List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);
//            if(list == null || list.size() == 0){
//            }else {
//                path = list.get(0);
//            }
//            if(TextUtils.isEmpty(path)){
//                DialogUtils.DialogOkMsg(mContext,"读取文档失败");
//                return;
//            }
//            openOrSend(path);
//        }
    }

    public void openOrSend(final String path){
        DialogUtils.DialogStringList(mContext, new String[]{"查看", "发送"}, new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0){
                    FileUtils.openFile(new File(path),mContext);
                }else {
//                    openBleNotify(path,UPGRADE_NOTICE);
                    getMessageAgreement(path,UPGRADE_NOTICE);
                }
            }
        });
    }


    private int packetCount;

    private void openBleNotify(final String filePath, final String type){
        BleUtils.notify(new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                sendProtocolUpdate(filePath,type);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
//                        BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                String sMes = HexUtil.bytesToAscii(data);
                BleLog.d("报文返回==" +Arrays.toString(data));
                BleLog.d("报文返回==" +HexUtil.bytesToHexString(data));
                if(HexUtil.bytesToHexString(data[0]).equals("FE") && data.length>=5){
                    String funCode = HexUtil.bytesToHexString(data[2]);  //功能码
                    switch (funCode){
                        case "52":          //升级数据请求 0x52 上行
                            packetCount = Integer.valueOf(HexUtil.bytesToHexString(data[5]));
                            break;
                    }
                }
            }

            @Override
            public void onError() {
                //关闭监听
                isFinish = true;
            }
        });

    }

    private void sendProtocolUpdate(String data,String type){
        BleUtils.write(getMessageAgreement(data,type ), new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {

            }

            @Override
            public void onWriteFailure(BleException exception) {

            }
        });
    }

    public static long MSG_AG_LEN = 200;
    private static byte[] getMessageAgreement(String data,String type){
        switch (type){
            case "4e":
                byte[]  agreement = MessageUtil.getUpgradeNotice(data);
                return agreement;
            case "52":
                break;
            case "46":
                break;
            case "47":
                break;
        }
        return new byte[0];
    }

}
